#include <iostream>
#include <regex>
#include <signal.h>
#include <stdio.h>
#include <string>
#include <unistd.h>
class UrlMatcher
{
    public:
    // 将URL规则转换为正则表达式
    static std::string convertToRegex(const std::string& urlPattern)
    {
        std::string result = urlPattern;

        // 转义特殊字符（除了*）
        std::regex specialChars(R"([.+?^${}()|[\]\\])");
        result = std::regex_replace(result, specialChars, R"(\$&)");

        // 将 * 替换为 .*
        std::regex asterisk(R"(\*)");
        result = std::regex_replace(result, asterisk, ".*");

        // 添加开始和结束锚点
        return "^" + result + "$";
    }

    // 测试URL是否匹配规则
    static bool matchUrl(const std::string& urlPattern, const std::string& testUrl)
    {
        std::string regexPattern = convertToRegex(urlPattern);
        std::regex urlRegex(regexPattern);
        return std::regex_match(testUrl, urlRegex);
    }
};

// std::regex_match - 完全匹配
void Test_regex_match()
{
    std::string text = "hell01234";
    std::regex pettern(R"(hell\d+)");

    // 基本匹配
    if (std::regex_match(text, pettern))
    {
        std::cout << "完全匹配成功\n";
    }

    // 获取匹配结果
    std::smatch result;
    if (std::regex_match(text, result, pettern))
    {
        std::cout << "匹配到" << result[0] << std::endl;
    }
    std::cout << "\n";
}
// std::regex_search - 部分匹配
void Test_regex_search()
{
    std::string text = "The price is $123.45 and tax is $12.34";
    std::regex pattern(R"(\$(\d+)\.(\d+))");

    std::smatch result;
    if (std::regex_search(text, result, pattern))
    {
        std::cout << "完整匹配: " << result[0] << "\n";
        std::cout << "美元部分: " << result[1] << "\n";
        std::cout << "美分部分: " << result[2] << "\n";
        std::cout << "未知部分: " << result[3] << "\n";
    }

    auto it = text.cbegin();
    while (std::regex_search(it, text.cend(), result, pattern))
    {
        std::cout << "找到： " << result[0] << "\n";
        std::cout << "suffix: " << result.suffix() << "\n";
        it = result.suffix().first;
    }
    std::cout << "\n";
}

// std::regex_replace - 替换
void Test_regex_replace()
{
    std::string text = "Hello World 123";
    std::regex pattern(R"(\d+)");

    // 简单替换
    auto result = std::regex_replace(text, pattern, "NUMBER");
    std::cout << "简单替换 " << result << "\n";

    // 使用捕获组替换
    std::string email = "user@explam.com";
    std::regex email_pattern(R"((\w+)@(\w+).(\w+))");
    auto formend = std::regex_replace(email, email_pattern, R"(用户名: \$1, 域名: \$2)");
    std::cout << formend << "\n";
    std::cout << std::regex_replace(email, email_pattern, R"($&)") << "\n";

    std::cout << "\n";
}

void sigalrm_fn(int sig)
{
    printf("alarm!\n");
    alarm(2);
    return;
}

int main()
{

    // Test_regex_match();
    // Test_regex_search();
    // Test_regex_replace();

#if 1
    // 测试示例1
    std::string pattern1 = "*/123.24*67";
    std::string regexPattern1 = UrlMatcher::convertToRegex(pattern1);
    std::cout << "规则: " << pattern1 << std::endl;
    std::cout << "正则: " << regexPattern1 << std::endl;

    // 测试匹配
    std::regex regex1(regexPattern1);
    std::cout << "匹配 'abc/123.24xyz67': " << std::regex_match(std::string("abc/123.24xyz67"), regex1) << std::endl;
    std::cout << "匹配 '/123.24567': " << std::regex_match(std::string("/123.24567"), regex1) << std::endl;

    std::cout << "\n"
              << std::string(50, '-') << "\n"
              << std::endl;

    // 测试示例2：您的URL规则
    std::string pattern2 = "http://msg.qy*.ne*t/v5/bi/*";
    std::string regexPattern2 = UrlMatcher::convertToRegex(pattern2);
    std::cout << "规则: " << pattern2 << std::endl;
    std::cout << "正则: " << regexPattern2 << std::endl;

    // 测试多个URL
    std::vector<std::string> testUrls = {
        "http://msg.qy.net/v5/bi/",
        "http://msg.qy.net/v5/bi/report",
        "http://msg.qy.net/v5/bi/data/123",
        "http://msg.qy.net/v5/api/test",
        "http://"};

    std::regex regex2(regexPattern2);
    for (const auto &url : testUrls)
    {
        bool matches = std::regex_match(url, regex2);
        std::cout << "匹配 '" << url << "': " << (matches ? "true" : "false") << std::endl;
    }
#endif

    return 0;
}

#if 0

#include <iostream>
#include <regex>
#include <string>
#include <vector>

class UrlMatcher {
public:
    // 将URL规则转换为正则表达式
    static std::string convertToRegex(const std::string& urlPattern) {
        std::string result = urlPattern;
        
        // 手动转义特殊字符（避免使用regex_replace，因为可能不稳定）
        std::string escaped;
        escaped.reserve(result.length() * 2);
        
        for (size_t i = 0; i < result.length(); ++i) {
            char c = result[i];
            switch (c) {
                case '.':
                case '+':
                case '?':
                case '^':
                case '$':
                case '{':
                case '}':
                case '(':
                case ')':
                case '|':
                case '[':
                case ']':
                case '\\':
                    escaped += '\\';
                    escaped += c;
                    break;
                case '*':
                    escaped += ".*";
                    break;
                default:
                    escaped += c;
                    break;
            }
        }
        
        return "^" + escaped + "$";
    }
    
    // 安全的正则匹配函数
    static bool matchUrl(const std::string& urlPattern, const std::string& testUrl) {
        try {
            std::string regexPattern = convertToRegex(urlPattern);
            
            // 创建正则表达式对象时使用异常处理
            std::regex urlRegex(regexPattern, std::regex_constants::ECMAScript);
            
            // 使用 regex_match 进行匹配
            return std::regex_match(testUrl, urlRegex);
            
        } catch (const std::regex_error& e) {
            std::cerr << "正则表达式错误: " << e.what() << " (错误代码: " << e.code() << ")" << std::endl;
            return false;
        } catch (const std::exception& e) {
            std::cerr << "其他错误: " << e.what() << std::endl;
            return false;
        }
    }
    
    // 批量匹配函数
    static void testMultipleUrls(const std::string& pattern, const std::vector<std::string>& urls) {
        try {
            std::string regexPattern = convertToRegex(pattern);
            std::regex urlRegex(regexPattern, std::regex_constants::ECMAScript);
            
            std::cout << "规则: " << pattern << std::endl;
            std::cout << "正则: " << regexPattern << std::endl;
            std::cout << "测试结果:" << std::endl;
            
            for (size_t i = 0; i < urls.size(); ++i) {
                bool matches = std::regex_match(urls[i], urlRegex);
                std::cout << "  '" << urls[i] << "': " << (matches ? "匹配" : "不匹配") << std::endl;
            }
            
        } catch (const std::regex_error& e) {
            std::cerr << "正则表达式错误: " << e.what() << std::endl;
        }
    }
};

int main() {
    std::cout << "=== 使用 regex_match 进行URL模式匹配 ===" << std::endl;
    
    // 测试示例1
    std::string pattern1 = "*/123.24*67";
    std::vector<std::string> testUrls1;
    testUrls1.push_back("abc/123.24xyz67");
    testUrls1.push_back("/123.24567");
    testUrls1.push_back("hello/123.24world67");
    testUrls1.push_back("123.24567");
    testUrls1.push_back("prefix/123.24middle67suffix");
    
    std::cout << "\n--- 测试1 ---" << std::endl;
    UrlMatcher::testMultipleUrls(pattern1, testUrls1);
    
    // 测试示例2
    std::string pattern2 = "http://msg.qy.net/v5/bi/*";
    std::vector<std::string> testUrls2;
    testUrls2.push_back("http://msg.qy.net/v5/bi/");
    testUrls2.push_back("http://msg.qy.net/v5/bi/report");
    testUrls2.push_back("http://msg.qy.net/v5/bi/data/123");
    testUrls2.push_back("http://msg.qy.net/v5/api/test");
    testUrls2.push_back("http://msg.qy.net/v5/bi/dashboard/analytics");
    
    std::cout << "\n--- 测试2 ---" << std::endl;
    UrlMatcher::testMultipleUrls(pattern2, testUrls2);
    
    // 单独测试一些URL
    std::cout << "\n--- 单独测试 ---" << std::endl;
    std::cout << "测试简单匹配:" << std::endl;
    std::cout << "  '*.jpg' 匹配 'photo.jpg': " << (UrlMatcher::matchUrl("*.jpg", "photo.jpg") ? "是" : "否") << std::endl;
    std::cout << "  '*.jpg' 匹配 'photo.png': " << (UrlMatcher::matchUrl("*.jpg", "photo.png") ? "是" : "否") << std::endl;
    std::cout << "  'http://*' 匹配 'http://example.com': " << (UrlMatcher::matchUrl("http://*", "http://example.com") ? "是" : "否") << std::endl;
    
    // 测试一些边界情况
    std::cout << "\n--- 边界情况测试 ---" << std::endl;
    try {
        std::regex simpleRegex("^.*$");
        std::cout << "基本正则表达式工作正常" << std::endl;
        
        std::string testStr = "hello world";
        bool result = std::regex_match(testStr, simpleRegex);
        std::cout << "regex_match 工作正常: " << (result ? "true" : "false") << std::endl;
        
    } catch (const std::exception& e) {
        std::cout << "正则表达式库存在问题: " << e.what() << std::endl;
        std::cout << "建议使用自定义匹配算法" << std::endl;
    }
    
    return 0;
}
#endif